from django.shortcuts import render

# Create your views here.
import json

from django.http import JsonResponse
from django.core.exceptions import ObjectDoesNotExist

from api.utils import success_response_with_data, failed_response_with_data, list_response
from api.utils_auth import get_is_frontend
from api.utils_material import get_record_tts, delete_file, get_all_material_subtype, material_subtype_name_zh, material_type_name_zh

from api.models import RecordTts, UploadRecord
from api.serializers import RecordTtsSerializer

from rest_framework import viewsets
from drf_yasg2.utils import swagger_auto_schema
from drf_yasg2 import openapi
from rest_framework.decorators import action

from api.mylogger import logger


class RecordTtsViewSet(viewsets.ModelViewSet):
    table_name = RecordTts._meta.db_table
    serializer_class = RecordTtsSerializer

    request_body = openapi.Schema(type=openapi.TYPE_OBJECT,
                                  required=['name', 'cover_url', 'file_url',
                                            'category'],
                                  properties={
                                      "name": openapi.Schema(type=openapi.TYPE_STRING, description="名称"),
                                      "material_type": openapi.Schema(type=openapi.TYPE_STRING, description="素材类型"),
                                      "material_subtype": openapi.Schema(type=openapi.TYPE_STRING, description="素材子类型"),
                                      "category": openapi.Schema(type=openapi.TYPE_STRING, description="素材分类"),
                                      "kind": openapi.Schema(type=openapi.TYPE_STRING, description="系统还是本地"),
                                      "enabled": openapi.Schema(type=openapi.TYPE_BOOLEAN, description="是否激活使用"),
                                      "cover_url": openapi.Schema(type=openapi.TYPE_STRING, description="封面图片路径"),
                                      "file_url": openapi.Schema(type=openapi.TYPE_STRING, description="文件实际路径"),
                                  }, )

    @swagger_auto_schema(operation_id='添加tts音频', tags=['ttsaudio'], request_body=request_body)
    @action(methods=['POST'], detail=False)
    def record_tts_add(self, request):
        data = json.loads(request.body.decode('utf8'))
        cover_url = data.get('cover_url', '')
        file_url = data.get('file_url',  '')
        category = data.get('category', '')

        serializer = RecordTtsSerializer(data=data)
        if serializer.is_valid():
            res = serializer.save()
            # 上传的照片url状态置为True
            if cover_url != '':
                ret1 = UploadRecord.objects.filter(urlpath=cover_url).update(status=True)
                print(f"ret1 is {ret1}")
            if file_url != '':
                ret2 = UploadRecord.objects.filter(urlpath=file_url).update(status=True)
                print(f"ret2 is {ret2}")
            res_data = {
                "table_name": self.table_name,
                "id": res.id,
            }
            return success_response_with_data(res_data, msg="新增tts音频成功")
        return JsonResponse(serializer.errors, status=400)

    @swagger_auto_schema(operation_id='删除tts音频', tags=['ttsaudio'], request_body=openapi.Schema(
        type=openapi.TYPE_OBJECT,
        properties={
            "dbid": openapi.Schema(type=openapi.TYPE_INTEGER, description="素材表的内部Id"),
        },
    ))
    @action(methods=['POST'], detail=False)
    def record_tts_del(self, request):
        data = json.loads(request.body.decode('utf8'))
        db_id = data.get('id', None)
        # 上传的照片url状态置为False
        one_obj = get_record_tts(db_id)
        cover_url = one_obj.get('cover_url', '')
        file_url = one_obj.get('file_url', '')

        if cover_url != '':
            UploadRecord.objects.filter(urlpath=cover_url).delete()
            delete_file(cover_url)
        if file_url != '':
            UploadRecord.objects.filter(urlpath=file_url).delete()
            delete_file(file_url)
        deleted_cnt, _ = RecordTts.objects.filter(id=db_id).delete()
        res_data = {
            "table_name": self.table_name,
            "info": "删除" + str(deleted_cnt) + "条记录!",
            "rows_deleted": deleted_cnt
        }
        return success_response_with_data(res_data, msg="删除记录成功!")

    @swagger_auto_schema(operation_id='单条tts音频信息', tags=['ttsaudio'], request_body=openapi.Schema(
        type=openapi.TYPE_OBJECT,
        properties={
            "id": openapi.Schema(type=openapi.TYPE_INTEGER, description="素材的内部Id"),
        },
    ))
    @action(methods=['POST'], detail=False)
    def record_tts_one(self, request):
        data = json.loads(request.body.decode('utf8'))
        db_id = data.get('id', None)
        try:
            qry = RecordTts.objects.get(id=db_id)
            serializer = RecordTtsSerializer(qry)
            return success_response_with_data(serializer.data, msg=self.table_name + "查询对象成功!")
        except ObjectDoesNotExist:
            return failed_response_with_data(None, msg=self.table_name + f"未查到id为{db_id}的素材!")

    request_body_mod = openapi.Schema(type=openapi.TYPE_OBJECT,
                                      required=['id', 'name', 'userid', 'username', 'mongoid'],
                                      properties={
                                          "id": openapi.Schema(type=openapi.TYPE_INTEGER, description="内部Id"),
                                          "name": openapi.Schema(type=openapi.TYPE_STRING, description="名称"),
                                          "material_subtype": openapi.Schema(type=openapi.TYPE_STRING, description="素材子类型"),
                                          "cover_url": openapi.Schema(type=openapi.TYPE_STRING,
                                                                      description="封面图片路径"),
                                          "file_url": openapi.Schema(type=openapi.TYPE_STRING,
                                                                     description="文件实际路径"),
                                          "category": openapi.Schema(type=openapi.TYPE_STRING, description="素材分类"),
                                      }, )

    @swagger_auto_schema(operation_id='修改tts音频', tags=['ttsaudio'], request_body=request_body_mod)
    @action(methods=['POST'], detail=False)
    def record_tts_mod(self, request):
        data = json.loads(request.body.decode('utf8'))
        db_id = data.get('id', None)

        cover_url = data.get('cover_url', '')
        file_url = data.get('file_url',  '')
        category = data.get('category', '')

        if db_id is None:
            return failed_response_with_data(msg="没有id, 修改不了")
        print(f"cover_url is {cover_url},file_url is {file_url}")

        serializer = RecordTtsSerializer(data=data)
        if serializer.is_valid():
            try:
                # 将文件路径做个false标志，过一段时候可以定期删除
                if 'cover_url' in data or 'file_url' in data :
                    old_one_obj = get_record_tts(db_id)
                    cover_url = old_one_obj.get('cover_url', '')
                    file_url = old_one_obj.get('file_url', '')
                    if cover_url != '':
                        UploadRecord.objects.filter(urlpath=cover_url).update(status=False)
                    if file_url != '':
                        UploadRecord.objects.filter(urlpath=file_url).update(status=False)

                db_ret = serializer.update(instance=RecordTts.objects.get(id=db_id), validated_data=data)
                logger.debug(f"db_ret {db_ret}")
                # 将文件路径做个true标志，修改后的文件不能删除，置为true
                if 'cover_url' in data or 'file_url' in data:
                    new_one_obj = get_record_tts(db_id)
                    cover_url = new_one_obj.get('cover_url', '')
                    file_url = new_one_obj.get('file_url', '')
                    if cover_url != '':
                        UploadRecord.objects.filter(urlpath=cover_url).update(status=True)
                    if file_url != '':
                        UploadRecord.objects.filter(urlpath=file_url).update(status=True)

                res_data = {
                    "table_name": self.table_name,
                    "id": db_ret.id
                }
                return success_response_with_data(res_data, msg="修改记录成功!")
            except ObjectDoesNotExist:
                return failed_response_with_data(msg=self.table_name+f"没有被修改,未发现id为{db_id}的记录")
        return JsonResponse(serializer.errors, status=400)

    @swagger_auto_schema(operation_id='tts音频列表查询', tags=['ttsaudio'],
                         method='POST',
                         request_body=openapi.Schema(
                             type=openapi.TYPE_OBJECT,
                             properties={
                                 "category": openapi.Schema(type=openapi.TYPE_STRING, description="内部素材类型"),
                                 "material_type": openapi.Schema(type=openapi.TYPE_STRING, description="素材类型"),
                                 "material_subtype": openapi.Schema(type=openapi.TYPE_STRING, description="素材子分类"),
                                 "query": openapi.Schema(type=openapi.TYPE_STRING, description="名称的部分信息"),
                             },
                         )
                         )
    @action(methods=['POST'], detail=False)
    def record_tts_list(self, request):
        is_frontend = get_is_frontend(request)

        data = json.loads(request.body.decode('utf8'))
        current_page = data.get("pagenum", 1)
        page_size = data.get("pagesize", 10)
        query = data.get("query", '')
        material_type = data.get("material_type", '')
        material_subtype = data.get("material_subtype", '')
        category = data.get("category", '')

        if current_page < 1:
            current_page = 1
        # 为避免大数据量，用这种方式比较合适，不要用Paginator
        start_row = (current_page - 1) * page_size
        end_row = current_page * page_size

        try:
            objects = RecordTts.objects
            if material_type != '':
                objects = objects.filter(material_type=material_type)
            if material_subtype != '':
                objects = objects.filter(material_subtype=material_subtype)
            if category != '':
                objects = objects.filter(category=category)
            if len(query):
                objects = objects.filter(name__icontains=query)
            if is_frontend:
                objects = objects.filter(status=True)
            # objects = objects.filter(status=True)
            objects = objects.all()
            total = objects.count()
            rows = objects[start_row:end_row]
            logger.debug(f"rows.query {rows.query}")

        except ObjectDoesNotExist:
            logger.debug("没有发现记录")
            return list_response()

        subtype_all = get_all_material_subtype()
        # print('subtype_all',subtype_all)
        material_list = RecordTtsSerializer(rows, many=True).data
        for index in range(len(material_list)):
            row = material_list[index]
            material_type = row["material_type"]
            material_subtype = row["material_subtype"]
            row["material_type_name_zh"] = material_type_name_zh(material_type)
            row["material_subtype_name_zh"] = material_subtype_name_zh(subtype_all, material_type, material_subtype)

        return list_response(material_list, total, page_size, current_page, self.table_name)

